﻿using Aliyun.OSS.Common;
using Aliyun.OSS;
using System;
using System.IO;
using InfonavaEye.model.wjapi;
using InfonavaEye.model;
using InfonavaEye.Service;
using System.Windows.Forms;
using System.Management.Instrumentation;

namespace InfonavaEye.components
{
    public class AliyunOSSSrvice
    {


        private static AliyunOSSSrvice instance=null;
        public static OssClient aliyunOSSInstance;

        public static StorageConfig oSSConfig;

        private AliyunOSSSrvice() {
            initAliyunOssClient();
        }
        public static AliyunOSSSrvice Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new AliyunOSSSrvice();

                }
                return instance;
            }
        }

        /// <summary>
        /// 初始化aliyunoss链接客户端
        /// </summary>
        public void initAliyunOssClient()
        {
            if (aliyunOSSInstance == null)
            {
                oSSConfig = WujingConfigService.StorageConfig;
                string accessKeyId = oSSConfig.AccessKeyId;
                string accessKeySecret = oSSConfig.AccessKeySecret;
                string endpoint = oSSConfig.Endpoint;
                var conf = new ClientConfiguration();
                conf.MaxErrorRetry = 3;
                conf.ConnectionTimeout = 5000;
                conf.EnalbeMD5Check = false;
                aliyunOSSInstance = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
            }
        }
        
        /// <summary>
        /// 断点续传上传
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public UploadFileResponse UploadFile(UploadFileParams file)
        {
            try
            {
               UploadObjectRequest request = new UploadObjectRequest(oSSConfig.bucketName,
                                file.fileName, file.filePath)
                {
                    PartSize = 8 * 1024 * 1024,
                    ParallelThreadCount = 3,
                    CheckpointDir = oSSConfig.CheckpointDir,
                };
                //request.StreamTransferProgress += ResumableUploadProgress;
              /* ObjectMetadata om = new ObjectMetadata();
                om.AddHeader("ScanSN", file.ScanSN);
                om.AddHeader("BoxTemplateCode", file.BoxTemplateCode);
                om.AddHeader("Segment", file.Segment);
                om.AddHeader("rowNumber", file.rowNumber);
                om.AddHeader("columnNumber", file.columnNumber);
                request.Metadata = om;*/
                PutObjectResult putResult = aliyunOSSInstance.ResumableUploadObject(request);
                UploadFileResponse response = new UploadFileResponse();
                response.Success = true;
                response.ServerType = "AliyunOSS";
                response.ContentLength = putResult.ContentLength;
                response.FileUrl = oSSConfig.Endpoint +"/"+oSSConfig.bucketName+"/"+file.fileName;
               // response.FileUrl = file.fileName;
                response.FileId = putResult.ETag;
                Console.WriteLine("Aliyun OSS Resumable upload object:{0},{1},ETag:{2} succeeded", file.filePath, file.fileName, putResult.ETag);
                return response;
            }
            catch (OssException ex)
            {
                Console.WriteLine("OSS Upload Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("OSS Upload Failed with error info: {0}", ex.Message);
            }
            return new UploadFileResponse()
            {
                Success = false,
            };
        }
        /// <summary>
        /// 断点续传上传进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /* public void ResumableUploadProgress(object sender, StreamTransferProgressArgs args) {
             _logger.LogInformation("_transferred:{0},  TotalBytes:{1}", args.TransferredBytes,args.TotalBytes);
         }*/
    }
}
